package android.hoopmedia.hoopmediaplayerdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.arenacloud.broadcast.android.ArenaCloudConfig;
import com.arenacloud.broadcast.android.BroadcastView;
import com.arenacloud.broadcast.android.streaming.AspectFrameLayout;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import com.arenacloud.broadcast.android.streaming.AudioEncoderConfig;

public class AcBroadcastActivity extends Activity implements BroadcastView.BroadcastStatusCallback, BroadcastView.ScreenShotCallback {

    private final static String TAG = "AcSdk_AcBroadcastActivity";
    private AspectFrameLayout mFrameLayout;
    private BroadcastView mBroadcastView;

    public String publicUrl;
    private String publicKey;
    private String id;
    private String password;
    private String ticket;
    private ZoomControls zoomControls;
    private int zoomValue = 0;
    private final static int ZOOM_STEP = 20;

    final int WHAT = 102;
    private Timer timer;
    private TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        Bundle extras = getIntent().getExtras();

        setContentView(R.layout.ac_broadcast_activity);

        TextView status = (TextView) findViewById(R.id.streamingStatus);
        status.setClickable(true);
        status.setFocusable(true);

        status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout cLayout = (LinearLayout) findViewById(R.id.info_display);

                if (cLayout.getVisibility() == View.VISIBLE) {
                    cLayout.setVisibility(View.INVISIBLE);
                } else {
                    cLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        mFrameLayout = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl);
        mBroadcastView = (BroadcastView) findViewById(R.id.cameraPreview_surfaceView);
        String pubKey = "fef19718136b161290d8d116b9912810";
        mBroadcastView.initBroadcast(extras, pubKey, this);

        if (mBroadcastView.getAspectRatio() != 0) {
            mFrameLayout.setAspectRatio(mBroadcastView.getAspectRatio());
        }

        mBroadcastView.setBroadcastStatusCallback(this);
        mBroadcastView.setScreenShotCallback(this);
        mBroadcastView.setBitrate(800000);

        publicUrl = extras.getString("publicUrl");
        publicKey = extras.getString("publicKey");
        id = extras.getString("id");
        password = extras.getString("password");
        ticket = extras.getString("ticket");

        ArenaCloudConfig config = new ArenaCloudConfig();
        config.setPublicKey(publicKey);

        zoomControls = (ZoomControls) findViewById(R.id.zoomControlId);
        zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if ((null == zoomControls) || (null == mBroadcastView)) {
                    return;
                }
                boolean isEnable = true;
                zoomControls.setIsZoomOutEnabled(true);
                if (zoomValue > ZOOM_STEP) {
                    zoomValue -= ZOOM_STEP;
                } else {
                    zoomValue = BroadcastView.CAMERA_ZOOM_MIN;
                }
                if (BroadcastView.CAMERA_ZOOM_MIN == zoomValue) {
                    isEnable = false;
                }
                zoomControls.setIsZoomInEnabled(isEnable);
                mBroadcastView.onFocusZoom(zoomValue);
            }
        });

        zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if ((null == zoomControls) || (null == mBroadcastView)) {
                    return;
                }
                boolean isEnable = true;
                zoomControls.setIsZoomInEnabled(true);
                if (zoomValue < BroadcastView.CAMERA_ZOOM_MAX) {
                    zoomValue += ZOOM_STEP;
                } else {
                    zoomValue = BroadcastView.CAMERA_ZOOM_MAX;
                }
                if (BroadcastView.CAMERA_ZOOM_MAX == zoomValue) {
                    isEnable = false;
                }
                zoomControls.setIsZoomOutEnabled(isEnable);
                mBroadcastView.onFocusZoom(zoomValue);
            }
        });



        task = new TimerTask() {
            @Override
            public void run() {
                // 更新数据
                Message message = new Message();
                message.what = WHAT;
                message.obj = mBroadcastView;
                handler.sendMessage(message);
            }
        };

        timer = new Timer();
        // 参数：
        // 1000，延时1秒后执行。
        // 2000，每隔2秒执行1次task。
        timer.schedule(task, 1000, 1000);
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT: {
                    BroadcastView view = (BroadcastView) msg.obj;
                    Log.d(TAG, "test");

                    String strFormat;
                    strFormat = "video param \n";
                    strFormat += "     width:" + view.getEncodeWidth() + "\n";
                    strFormat += "     heigh:" + view.getEncodeHeight() + "\n";
                    strFormat += "     fps:" + view.getFps() + "\n";
                    strFormat += "     bitrate:" + view.getBitRate();

                    AudioEncoderConfig audio = view.GetAudioConfig();
                    strFormat += "\naudio param \n";
                    strFormat += "     SampleRate:" + audio.getSampleRate() + "\n";
                    strFormat += "     Channels:" + audio.getNumChannels() + "\n";
                    strFormat += "     bitrate:" + audio.getBitrate() + "\n";
                    strFormat += "     bandbitrate:" + view.apiGetStreamBitrate() + "\n";
                    strFormat += "url: \n" + publicUrl;

                    TextView text = (TextView) findViewById(R.id.vedio);
                    text.setText(strFormat);
                }
                break;
            }
        }
    };

    public boolean onTouchEvent(MotionEvent event) {
        if (null == mBroadcastView) {
            return false;
        }

        int bt = mBroadcastView.apiGetStreamBitrate();
        Log.w(TAG, "current-bitrate:"+bt);
        mBroadcastView.onTouchFocus(event);
        return super.onTouchEvent(event);
    }

    public static String getTouchAction(int actionId) {
        String actionName = "Unknow:id=" + actionId;
        switch (actionId) {
            case MotionEvent.ACTION_DOWN:
                actionName = "ACTION_DOWN";
                break;
            case MotionEvent.ACTION_MOVE:
                actionName = "ACTION_MOVE";
                break;
            case MotionEvent.ACTION_UP:
                actionName = "ACTION_UP";
                break;
            case MotionEvent.ACTION_CANCEL:
                actionName = "ACTION_CANCEL";
                break;
            case MotionEvent.ACTION_OUTSIDE:
                actionName = "ACTION_OUTSIDE";
                break;
        }
        return actionName;
    }

    public void onClick(View v) {
        if (null == mBroadcastView) {
            return;
        }
        int i = v.getId();
        if (i == R.id.toggleRecording_button) {


            new  Thread(new Runnable() {
                @Override
                public void run() {
                    if (mBroadcastView.isRecordingEnabled()) {
                        mBroadcastView.toggleRecording();
                    } else {

                        long lTime = System.currentTimeMillis();
                        String pubUrl = "rtmp://huputv-ali-pub.arenacdn.com/prod/live";
                        String liveUrl = "rtmp://huputv-ali-live.arenacdn.com/prod/live";
                        String pukRoom = "10241";

                        if (publicUrl.isEmpty()) {
                            publicUrl = "rtmp://huputv-ali-pub.arenacdn.com/prod/live";
                        }else{
                            pubUrl = publicUrl;
                        }

                        String path = pubUrl;
                        String prjId =  "f88624ad0cf2380b22100336";
                        String deviceId = "123456789";
                        String roomId = "12305";
                        String roomName = "jingcaijinqiu";
                        String channelId = "360market";
                        boolean isRegister = false;
                        String reserved = "reserved";

                        mBroadcastView.setPublishPara(path, prjId, deviceId, roomId, roomName, channelId, isRegister, reserved);
                        mBroadcastView.toggleRecording();
                    }
                }
            }).start();
        } else if (i == R.id.toggleSwitch_button) {
            mBroadcastView.switchCamera();
        } else if (i == R.id.toggleScreenShot_button) {
            mBroadcastView.takeScreenShot();
        } else if (i == R.id.restart_button) {
            new  Thread(new Runnable() {
                @Override
                public void run() {
                    mBroadcastView.apiRestartPush();
                }
            }).start();
        }
    }

    @Override
    protected void onResume() {
        Log.w(TAG, "Act-on-Resume-run");
		mBroadcastView.onResumeHandler();
        super.onResume();
        Log.w(TAG, "Act-on-Resume-ext");
    }

    @Override
    protected void onPause() {
        Log.w(TAG, "Act-on-Pause-run");
        super.onPause();
        mBroadcastView.onPauseHandler();
        Log.w(TAG, "Act-on-Pause-ext");
    }

    @Override
    protected void onDestroy() {
        Log.w(TAG, "Act-on-Destroy-run");
        mBroadcastView.onDestroyHandler();
        super.onDestroy();
        Log.w(TAG, "Act-on-Destroy-ext");
    }

    static boolean bReconnect = true;

    @Override
    public void broadcastStatusUpdate(final BroadcastView.BROADCAST_STATE state) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView statusTextView = (TextView) findViewById(R.id.streamingStatus);

                String statusText;
                switch (state) {
                    case PREPARING:
                        statusText = "Preparing";
                        break;
                    case CONNECTING:
                        statusText = "Connecting";
                        break;
                    case READY:
                        statusText = "Ready";

                        break;
                    case STREAMING:
                        statusText = "Streaming";

                        break;
                    case SHUTDOWN:
                        statusText = "Shutdown";
                        break;
                    case DISCONNECT:
                        statusText = "Disconnect";

                        long startRunMs = 0;
                        if (0 == startRunMs) {
                            startRunMs = System.currentTimeMillis();
                        }

                        // 如果点击了停止，则需要停止直播，无线重连
                        if (mBroadcastView.mRecordClick == true){
                            mBroadcastView.apiStopRecording();
                            mBroadcastView.mRecordClick = false;
                            break;
                        }


                        if (mBroadcastView.apiGetAutoConnect()){
                            long curMs = System.currentTimeMillis();

                            if (bReconnect){
                                bReconnect = false;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        try {
                                            Thread.sleep(3000);
                                            mBroadcastView.apiRestartPush();
                                            bReconnect = true;
                                        }
                                        catch (Exception e){

                                        }
                                    }
                                }).start();
                            }
                        }
                        break;
                    default:
                        statusText = "Unknown";
                        break;
                }
                statusTextView.setText(statusText);
            }
        });
    }

    private Bitmap bitmap;

    @Override
    public void onScreenShotEvent(final Bitmap bitmap) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                File file = new File("/sdcard" + "/ArenaCloud/ScreenShot/");
                if (!file.exists()) {
                    file.mkdir();
                }

                String savePath = "/sdcard" + "/ArenaCloud/ScreenShot/" + System.currentTimeMillis() + ".jpeg";
                try {
                    FileOutputStream fout = new FileOutputStream(savePath);
                    BufferedOutputStream bos = new BufferedOutputStream(fout);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    bos.flush();
                    bos.close();

                    bitmap.recycle();

                    Toast.makeText(AcBroadcastActivity.this, "YOU HAVE SAVED A SCREENSHOT",
                            Toast.LENGTH_LONG).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
